<template>
  <div class="header">
    <a href="#/">
      <img src="@/assets/logo.png" alt class="logo" />
      <span class="company">会员管理系统</span>
    </a>

    <el-dropdown trigger="click" @command="handleCommand">
      <span class="el-dropdown-link">
        {{user.name}}
        <i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item icon="el-icon-edit" command="a">修改密码</el-dropdown-item>
        <el-dropdown-item icon="el-icon-loading" command="b">退出系统</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>

    <!-- 修改密码对话框组件 -->
    <el-dialog title="更改密码" :visible.sync="dialogFormVisible" width="400px">
      <el-form
        :rules="rules"
        ref="form"
        :model="changePsd"
        label-width="110px"
        label-position="right"
        style="width:310px"
        status-icon
      >
        <el-form-item label="旧密码" prop="odlPassword">
          <el-input type="text" v-model="changePsd.odlPassword"></el-input>
        </el-form-item>
        <el-form-item label="请输入新密码" prop="newPassword">
          <el-input type="password" v-model="changePsd.newPassword"></el-input>
        </el-form-item>
        <el-form-item label="请确认密码" prop="surePassword">
          <el-input type="password" v-model="changePsd.surePassword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
          <el-button @click="reset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
//导入退出登录系统的api
import { logOut } from "@/api/login";

import passwordApi from "@/api/password";
export default {
  data() {
    //在return上自定义校验规则

    const validateOldPass = (rule, value, callback) => {
      //  value就是用户输入的旧密码
      //  console.log(value);
      //当失去输入旧密码焦点的时候就 调用后台接口进行校验
      passwordApi.checkPsd(this.user.id, value).then(response => {
        const checkedResponseData = response.data;
        if (checkedResponseData.flag) {
          callback();
          //验证不通过
        } else {
          callback(new Error(checkedResponseData.message));
        }
      });
    };

    const validateSurePass = (rule, value, callback) => {
      //如果确认密码和输入的新密码 一致
      if (value !== this.changePsd.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      //获取本地存储用户信息对象
      user: JSON.parse(localStorage.getItem("x-msm-user")),
      dialogFormVisible: false,
      changePsd: {
        odlPassword: "",
        newPassword: "",
        surePassword: ""
      },
      rules: {
        odlPassword: [
          { required: true, message: "旧密码不能为空", trigger: "blur" },
          { validator: validateOldPass, trigger: "blur" }
        ],

        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" }
        ],

        surePassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { validator: validateSurePass, trigger: "change" }
        ]
      }
    };
  },

  methods: {
    handleCommand(command) {
      switch (command) {
        case "a":
          this.updatePsd();

          break;

        case "b":
          this.exitSystem();

          break;

        default:
          break;
      }
    },
    exitSystem() {
      // //退出系统
      // //  this.$message(`退出系统`);
      // const token = localStorage.getItem("x-msm-token");
      // logOut(token).then(response => {
      //   const resData = response.data;
      //   //如果退出成功
      //   if (resData.flag) {
      //     //1.清除本地存储的数据
      //     localStorage.removeItem("x-msm-token");
      //     localStorage.removeItem("x-msm-user");
      //     //2.回到登录页面
      //     this.$router.push("/login");
      //     //退出失败
      //   } else {
      //     this.$message({
      //       message: resData.message,
      //       type: "warning",
      //       duration: 5000 //警告停留时间
      //     });
      //   }
      // });
      this.$store.dispatch('Logout').then(res=>{
        const resData=res
        if(res.flag){
          this.$message({
            message:resData.message,
            type:'success'
          })
          this.$router.push('/login')

        }else {
            this.$message({
            message:resData.message,
            type:'warning',
             duration: 5000 //警告停留时间
          })
        }
      })
    },
    updatePsd() {
      this.dialogFormVisible = true;
      //让对话框框弹出来之后 就执行异步函数 this.nextTick
      //在异步函数调用同步函数 
      this.$nextTick(()=>{
        this.$refs['form'].resetFields();
      });
    },
    //重置对话框表单
    reset(formName) {
      this.$refs[formName].resetFields();
    },
    //
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        //校验成功
        if (valid) {
          passwordApi
            .updatePsd(this.user.id, this.changePsd.surePassword)
            .then(response => {
              const updatedResponseData = response.data;
              //如果密码修改成功
              if (updatedResponseData.flag) {
                //1.提示信息
                this.$message({
                  showClose: true,
                  message: updatedResponseData.message+'请重新登录',
                  type: "success"
                });
                //2.退出对话框
                this. dialogFormVisible=false;
                //3.退出到登录界面
                  this.exitSystem();
                 
                //
                //密码修改失败
              } else {
                this.$message({
                  showClose: true,
                  message: updatedResponseData.message,
                  type: "error"
                });
              }
            });
          //校验失败
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
a {
  text-decoration: none;
}
.logo {
  width: 30px;
  vertical-align: middle;
  padding: 0 10px 0 50px;
}
.company {
  position: absolute;
  color: #fff;
}
.el-dropdown {
  float: right;
  margin-right: 40px;
}
.el-dropdown-link {
  cursor: pointer;
  color: #fff;
}
</style>